var express = require('express');
var router = express.Router();
const UniSMS = require('unisms').default
var { backgrounduserModel, identityModel, PermissionsModel, Publish_an_eventModel, UsersModel, commodityModel, participate_activityModel, OrderModel } = require('../../model/model')
var multiparty = require('multiparty');
// 使用腾讯云api
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");


// token key值
var { ACCESS_KEY, REFRESH_KEY } = require('./token_keys/keys')
// 封装创建，验证token
var { generateToken, verifyToken } = require('./generate_token/generateToken')
// token验证 中间件导入
var { short_checkAuth, length_checkAuth } = require('./verify_token/verify_Token')


// 双token登录
router.post('/login', async (req, res) => {
  let userdata = req.body
  let data = await backgrounduserModel.find({ user: userdata.user, password: userdata.password })
  if (data.length > 0) {
    let payload = {
      _id: data[0]._id,
      authentic_name: data[0].authentic_name,
    }
    //生成token
    let access_token = generateToken(payload, ACCESS_KEY, '1h')
    let REFRESH_token = generateToken(payload, REFRESH_KEY, 60 * 60 * 24 * 7)
    res.send({
      code: 200,
      msg: '登录成功',
      identity: data[0].identity_name,
      authentic_name: data[0].authentic_name,
      avatar: data[0].avatar,
      data: {
        access_token,
        REFRESH_token
      }
    })
  } else {
    res.send({
      code: 400,
      msg: '登录失败,账号或密码错误'
    })
  }
})

// 人脸识别登录
router.post('/face_login', async (req, res) => {
  let userdata = req.body.imageurl._rawValue
  // console.log(userdata);
  const IaiClient = tencentcloud.iai.v20200303.Client;

  const clientConfig = {
    credential: {
      //自己的腾讯secretId
      secretId: "AKIDTogqsgGcuLhsvrgMtGiCtTp10lIbzFRZ",
      //自己的腾讯密匙
      secretKey: "zlPr66ykv56tVt3yfASWMyNYVBg6MQd4",
    },
    region: "ap-beijing",  //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };

  const client = new IaiClient(clientConfig);

  const params = {
    "GroupIds": [  //你创建的人员库ID
      "123123"
    ],
    "Image": userdata,  //图片的base64格式编码
    "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
  };
  //doc为人脸识别后的返回信息
  let doc = await client.SearchFaces(params)
  // console.log(doc, 'doc');

  if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
    // console.log(personName, 'personNume');
    let user = await backgrounduserModel.find({ authentic_name: personName })

    if (user.length == 1) {
      let payload = {
        _id: user[0]._id,
        authentic_name: user[0].authentic_name,
      }

      let access_token = generateToken(payload, ACCESS_KEY, '1h')
      let REFRESH_token = generateToken(payload, REFRESH_KEY, 60 * 60 * 24 * 7)
      res.send({
        code: 200,
        msg: '登录成功',
        identity: user[0].identity_name,
        authentic_name: user[0].authentic_name,
        avatar: user[0].avatar,
        data: {
          access_token,
          REFRESH_token
        }
      })
    } else {
      res.send({
        code: 404,
        msg: '查无此人'
      })
    }

  }
})

// 获取验证码,向手机发送短信，获取验证码
router.get('/getyzm', async (req, res) => {
  const client = new UniSMS({
    accessKeyId: 'PYqSuZEnwZjnsxvoXFhYRWsi59ZARzufsKDk8U4D7mvGret3X',
    accessKeySecret: 'NRz14j3Yz7v6xX8djJoJNoW6N9nLDN', //当你实名认证之后就会自动生成ID，直接复制就行
  })
  const bind_contact = req.query.bind_contact
  //生成随机的四位数验证码，也可以修改成其他几位数验证码
  const len = Math.floor(1000 + Math.random() * 9000)
  //  发送短信
  client.send({
    to: bind_contact,
    signature: '董起嘉',
    templateId: 'pub_verif_basic', //短信报备中模板管理，在里面随便复制一个通道就可以
    templateData: {
      code: len,
    },
  }).then(ret => {
    res.send({ code: ret.code, len: len })
  }).catch(err => {
    console.log(err);
  })
})

// 修改密码
router.put('/Confirm_password', async (req, res) => {
  let bind_contact = req.body.bind_contact
  let password = req.body.password
  await backgrounduserModel.updateOne({ bind_contact: bind_contact }, { password: password })
  res.send({
    code: 200,
    msg: '修改成功'
  })
})

// 权限渲染接口
router.get('/getPermissions', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let claim = req.claim
  // backgrounduserModel,identityModel,PermissionsModel
  let user = await backgrounduserModel.find({ _id: claim._id })
  let COS = await identityModel.find({ _id: user[0].identity_id })
  let quan_list = await PermissionsModel.find().lean()

  let list = []
  COS[0].Permissions_id.forEach(ID => {
    quan_list.forEach(item => {
      if (String(ID) == String(item._id)) {
        list.push(item)
      }
    })
  })
  let quanobj = {}
  list.forEach(item => {
    quanobj[item._id] = item
  })
  let aaa = []
  list.forEach(item => {
    if (!item.pid) {
      aaa.push(item)
    } else {
      if (!quanobj[item.pid]['children']) {
        quanobj[item.pid]['children'] = []
      }
      if (quanobj[item.pid]) {
        quanobj[item.pid]['children'].push(item)
      }
    }
  })
  res.send({
    cos_name: COS[0].cosname,
    info_list: aaa,
    code: 200
  })
})

// 添加活动
router.post('/add_activity', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.body
  await Publish_an_eventModel.create(data)
  res.send({
    code: 200,
    msg: '添加成功',
  })
})

// 图片上传
router.post('/uploadimg', async (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (err, a, b) => {
    res.send({
      code: 200,
      msg: "http://localhost:3000/" + b.file[0].path,
    })
  })
})

// 删除活动
router.get('/del_activity', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let _id = req.query._id
  await Publish_an_eventModel.deleteOne({ _id: _id })
  res.send({
    code: 200,
    msg: '删除成功',
  })
})

// 开启/关闭活动当前状态
router.get('/put_activity', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let _id = req.query._id
  let data = await Publish_an_eventModel.findOne({ _id: _id })
  if (data.Active_istrue) {
    await Publish_an_eventModel.updateOne({ _id: _id }, { Active_istrue: false })
    res.send({
      code: 200,
      msg: '关闭成功'
    })
  } else {
    await Publish_an_eventModel.updateOne({ _id: _id }, { Active_istrue: true })
    res.send({
      code: 200,
      msg: '开启成功'
    })
  }

})

// 获取所有发布的活动
router.get('/get_activity', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.query

  let arr = []
  if (data.active_name != '') {
    let rep = RegExp(data.active_name)
    arr.push({ activity_name: rep })
  }
  if (data.active_istrue != '') {
    arr.push({ Active_istrue: data.active_istrue })
  }
  if (data.activity_type != '') {
    arr.push({ activity_type: data.activity_type })
  }
  if (arr.length != 0) {
    let data = await Publish_an_eventModel.find({ $and: arr })
    res.send({
      code: 200,
      msg: '查询成功',
      data
    })
  } else {
    let data = await Publish_an_eventModel.find()
    res.send({
      code: 200,
      msg: '查询成功',
      data
    })
  }
})

// 获取要修改活动的数据
router.get('/get_updata_activify', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let _id = req.query.id
  let data = await Publish_an_eventModel.find({ _id: _id })
  res.send({
    code: 200,
    msg: '查询成功',
    data
  })
})
// 修改活动
router.post('/updata_activify', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.body
  await Publish_an_eventModel.updateOne({ _id: data._id }, data)
  res.send({
    code: 200,
    msg: '修改成功'
  })
})

// 获取所有不能使用积分换购的商品
router.get('/get_commodity_no', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let req1 = req.query

  let arr = []
  if (req1.commodity_name != '') {
    let name = RegExp(req1.name)
    arr.push({ commodity_name: name })
    arr.push({ commodity_istrue: false })
  }
  if (req1.commodity_type != '') {
    let type = RegExp(req1.commodity_type)
    arr.push({ commodity_type: type })
    arr.push({ commodity_istrue: false })
  }
  if (req1.max_commodity_price != '') {
    arr.push({ commodity_price: { $lte: req1.max_commodity_price } })
    arr.push({ commodity_istrue: false })
  }
  if (req1.small_commodity_price != '') {
    arr.push({ commodity_price: { $gte: req1.small_commodity_price } })
    arr.push({ commodity_istrue: false })
  }
  if (arr.length > 0) {
    let data = await commodityModel.find({ $and: arr })
    res.send({
      code: 200,
      msg: '查询成功',
      data
    })
  } else {
    let data = await commodityModel.find({ commodity_istrue: false })
    res.send({
      code: 200,
      msg: '查询成功',
      data
    })
  }

})

// 获取所有可以使用积分换购的商品
router.get('/get_commodity_yes', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let req1 = req.query
  let arr = []
  if (req1.commodity_name != '') {
    let name = RegExp(req1.name)
    arr.push({ commodity_name: name })
    arr.push({ commodity_istrue: true })
  }
  if (req1.commodity_type != '') {
    let type = RegExp(req1.commodity_type)
    arr.push({ commodity_type: type })
    arr.push({ commodity_istrue: true })
  }
  if (req1.max_commodity_jifen != '') {
    arr.push({ commodity_jifen: { $lte: req1.max_commodity_jifen } })
    arr.push({ commodity_istrue: true })
  }
  if (req1.small_commodity_jifen != '') {
    arr.push({ commodity_jifen: { $gte: req1.small_commodity_jifen } })
    arr.push({ commodity_istrue: true })
  }
  if (arr.length > 0) {
    let data = await commodityModel.find({ $and: arr })
    res.send({
      code: 200,
      msg: '查询成功',
      data
    })
  } else {
    let data = await commodityModel.find({ commodity_istrue: true })
    res.send({
      code: 200,
      msg: '查询成功',
      data
    })
  }
})
// 修改商品是否可以进行积分换购
router.post('/updata_commodity_istrue', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let _id = req.body._id
  let commodity = await commodityModel.findOne({ _id })
  if (commodity.commodity_istrue) {
    await commodityModel.updateOne({ _id }, { commodity_istrue: false })
    res.send({
      code: 200,
      msg: '修改成功'
    })
  } else {
    await commodityModel.updateOne({ _id }, { commodity_istrue: true })
    res.send({
      code: 200,
      msg: '修改成功'
    })
  }
})

// 添加商品
router.post('/Addcommodity', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.body
  await commodityModel.create(data)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

// 获取用户注册人数
router.get('/get_user', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = await UsersModel.find()
  let shiba = data.filter(item => item.age >= 18 && item.age <= 25)
  let erliu = data.filter(item => item.age >= 26 && item.age <= 35)
  let sanliu = data.filter(item => item.age >= 36 && item.age <= 45)
  let siliu = data.filter(item => item.age >= 46 && item.age <= 55)
  let wuliu = data.filter(item => item.age >= 56)
  res.send({
    code: 200,
    msg: "获取成功",
    userdata: data,
    data_all: data.length,
    data: {
      shiba: shiba.length,
      erliu: erliu.length,
      sanliu: sanliu.length,
      siliu: siliu.length,
      wuliu: wuliu.length
    }
  })
})
//获取用户购买数量
router.get('/get_background_user', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = await backgrounduserModel.find()
  let laoban = data.filter(item => item.identity_name == '老板')
  let jingli = data.filter(item => item.identity_name == '经理')
  let kefu = data.filter(item => item.identity_name == '客服')
  let xiaoshou = data.filter(item => item.identity_name == '柜台姐')
  res.send({
    code: 200,
    msg: '获取成功',
    data: data,
    usercount: {
      'laoban': laoban.length,
      'jingli': jingli.length,
      'kefu': kefu.length,
      'xiaoshou': xiaoshou.length
    }
  })
})

// 删除商品
router.post('/del_shangpin', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.body
  await commodityModel.deleteOne({ _id: data._id })
  res.send({
    code: 200,
    msg: '删除成功'
  })
})

// 获取修改的数据
router.get('/get_updatacommodity_data', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let _id = req.query
  let data = await commodityModel.findOne({ _id: _id._id })
  res.send({
    code: 200,
    msg: '获取成功',
    data: data
  })
})

// 修改商品数据
router.post('/updata_commodity', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let data = req.body
  await commodityModel.updateOne({ _id: data._id }, data)
  res.send({
    code: 200,
    msg: '修改成功'
  })
})


// 活动参与活动人员
router.get('/get_participate_activityModel', short_checkAuth(ACCESS_KEY), async (req, res) => {
  let getdata = req.query
  let arr = []
  if (getdata.name != '') {
    let name = RegExp(getdata.name)
    arr.push({ name: name })
  }
  if (getdata.activity_name != '') {
    let huodong_name = RegExp(getdata.activity_name)
    arr.push({ activity_name: huodong_name })
  }
  if (getdata.activity_jiangpin != '') {
    let jiangpin = RegExp(getdata.activity_jiangpin)
    arr.push({ activity_jiangpin: jiangpin })
  }
  if (getdata.activity_jiangpin_istrue != '') {
    arr.push({ activity_jiangpin_istrue: getdata.activity_jiangpin_istrue })
  }
  if (arr.length != 0) {
    let data = await participate_activityModel.find({ $and: arr })
    res.send({
      code: 200,
      msg: '获取成功',
      data
    })
  } else {
    console.log(getdata);
    let data = await participate_activityModel.find()
    res.send({
      code: 200,
      msg: '获取成功',
      data
    })
  }
})

// 删除参与活动人员信息
router.post('/delitem',short_checkAuth(ACCESS_KEY), async (req, res) => {
  let _id = req.body._id
  await participate_activityModel.deleteOne({ _id })
  res.send({
    code: 200,
    msg: '删除成功'
  })
})




// 刷新token
router.get('/refresh_token', length_checkAuth(REFRESH_KEY), async (req, res) => {
  let claim = req.claim  // 获取token中payload的信息
  let payload = {
    _id: claim._id,
    authentic_name: claim.authentic_name,
  }
  let access_token = generateToken(payload, ACCESS_KEY, '1h')
  res.send({
    code: 2000,
    msg: '刷新成功',
    access_token: access_token
  })
})





module.exports = router;
